package server;

import lombok.Data;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * Minicat的主类
 *
 * @author Fxz
 * @version 1.0
 * @date 2021-08-23 15:44
 */
@Data
public class BootStrap {

    /**
     * socket监听的端口
     */
    private Integer port = 8080;


    /**
     * Minicat启动需要初始化的一些操作
     */
    public void start() throws IOException {
        //完成Minicat1.0版本 (浏览器请求http://localhost:8080 返回一个固定的字符串到页面 "hello Minicat")
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("------Minicat start on port:"+port+" -------");

        // while (true){
        //     Socket socket = serverSocket.accept();
        //     //有了socket 接收到请求 获取输出流
        //     OutputStream outputStream = socket.getOutputStream();
        //     String data = "hello Minicat";
        //     String responseText =  HttpProtocolUtil.getHttpHeader200(data.getBytes().length)+data;
        //     outputStream.write(responseText.getBytes());
        //     socket.close();
        // }

        /**
         * 完成MiniCat V2.0
         * 需求：封装Request和Response对象 返回html静态资源文件
         */
        while (true){
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();

            //封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            response.outputHtml(request.getUrl());
            socket.close();
        }
    }


    /**
     * MiniCat的程序启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        BootStrap bootStrap = new BootStrap();
        try {
            //启动MiniCat
            bootStrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
